package com.snsoft.controllerTest;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.jsoup.Connection.Method;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;


/**
 * 
 * @copyright 神农大学生软件创新中心版权所有 (c) 2016
 * 
 * @author Mr. Soldier
 * 
 * @version 1.0
 * 
 * @date 2016年9月27日 上午9:54:31
 * 
 * @Description TODO
 * 
 *     类似于postman工具
 */
public class JsoupTestor {

	private Map<String, String> cookies;
	
	public JsoupTestor(){
		//需要根据实际情况修改下面三个参数
		this("test","123456");
	}
	
	/**
	 * 根据账号密码创建一个测试对象
	 * @param account
	 * @param password
	 */
	public JsoupTestor(String account, String password){
		cookies = login("http://localhost:8080/greenhouse/user", account, password);
	}
	
	/**
	 * 实际连接登录接口
	 * @param url
	 * @param account
	 * @param password
	 * 
	 * @return 返回cookie集合
	 */
	private Map<String, String> login(String url, String account, String password){
		try {
			Map<String, String> datas = new HashMap<String,String>();
			datas.put("method", "login");
			datas.put("userCode", account);
			datas.put("userPassWord", password);
			Response rs = Jsoup.connect(url).data(datas).method(Method.POST).timeout(50000).ignoreContentType(true).execute();
			System.out.println(rs.body());
			return rs.cookies();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 发送post请求
	 * @param url
	 * @param params
	 * @return
	 */
	public String doPost(String url, Map<String,String> params){
		if(params == null){
			params = new HashMap<String, String>();
		}
		try {
			return Jsoup.connect(url).cookies(cookies).data(params).timeout(5000).ignoreContentType(true).method(Method.POST).execute().body();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 发送get请求
	 * @param url
	 * @param params
	 * @return
	 */
	public String doGet(String url, Map<String,String> params){
		if(params == null){
			params = new HashMap<String, String>();
		}
		try {
			return Jsoup.connect(url).cookies(cookies).data(params).timeout(5000).ignoreContentType(true).method(Method.GET).execute().body();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
